import { defineStore } from "pinia";
import userApi, { type LoginModel, type RegisterModel } from '@/api/user'


export const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: localStorage.getItem('token'),//存储用户token
      userName: '',//存储用户姓名
      phone: ''//手机号
    }
  },
  actions: {
    //获取验证码
    async getCode(phone: string) {
      try {
        let result = await userApi.reqGetCode(phone)
        if (result && result.code === 200) {
          return result.data
        } else {
          return Promise.reject(result.message)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    //注册
    async register(data: RegisterModel) {
      try {
        let result = await userApi.reqRegister(data)
        if (result && result.code === 200) {
          return Promise.resolve(result.message)
        } else {
          return Promise.reject(result.message)
        }
      } catch (error) {
        return Promise.resolve(error)
      }


    },
    //登录
    async login(data: LoginModel) {
      try {
        //调用API,发送请求
        let result = await userApi.reqLogin(data)
        if (result && result.code === 200) {
          //将token存储到state中
          this.token = result.data.token
          //将token存储到本地
          localStorage.setItem('token', result.data.token)
        } else {
          return Promise.reject(result.message)
        }
      } catch (error) {
        console.log('登录失败请重试')
        return Promise.reject(error)
      }

    },
    //获取用户信息
    async getUserInfo() {
      try {
        //调用API发送请求,获取数据
        let result = await userApi.reqGetUserInfo()
        console.log(result)
        if (result && result.code === 200) {
          //把用户信息存储起来
          this.userName = result.data.name
          this.phone = result.data.loginName
        } else {
          return Promise.reject(result.message)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    //退出登录
    async loginOut() {
      try {
        let result = await userApi.reqLoginOut()
        if (result && result.code === 200) {
          //清除token
          this.token = ''
          localStorage.removeItem('token')
        } else {
          console.log(result.message)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
})